import { MaterialIcons } from '@expo/vector-icons';
import React, { useRef, useState } from 'react';
import { Animated, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

type Tool = {
    key: string;
    label: string;
    icon: string;
};

type Props = {
    tools: Tool[];
    currentTool: string;
    onToolPress: (tool: string) => void;
    onConfirm: () => void;
    onCancel: () => void;
    children?: React.ReactNode;
};

/**
 * 通用的底部工具栏和弹出层组件
 */
export default function ToolbarWithBottomSheet({
    tools,
    currentTool,
    onToolPress,
    onConfirm,
    onCancel,
    children
}: Props) {
    const [showBottomSheet, setShowBottomSheet] = useState(false);
    const bottomSheetTranslateY = useRef(new Animated.Value(300)).current;

    // 处理工具栏点击
    const handleToolPress = (tool: string) => {
        if (currentTool === tool) {
            // 如果点击当前工具，切换底部弹出层显示状态
            if (showBottomSheet) {
                // 隐藏弹出层 - 工具栏向下滑出
                setShowBottomSheet(false);
                Animated.timing(bottomSheetTranslateY, {
                    toValue: 300,
                    duration: 300,
                    useNativeDriver: true,
                }).start();
            } else {
                // 显示弹出层 - 工具栏向上滑入
                setShowBottomSheet(true);
                Animated.timing(bottomSheetTranslateY, {
                    toValue: 0,
                    duration: 300,
                    useNativeDriver: true,
                }).start();
            }
        } else {
            // 切换到新的工具，总是显示弹出层
            onToolPress(tool);
            setShowBottomSheet(true);

            Animated.timing(bottomSheetTranslateY, {
                toValue: 0,
                duration: 300,
                useNativeDriver: true,
            }).start();
        }
    };

    // 处理底部弹出层关闭
    const handleCloseBottomSheet = () => {
        setShowBottomSheet(false);
        Animated.timing(bottomSheetTranslateY, {
            toValue: 300,
            duration: 300,
            useNativeDriver: true,
        }).start();
        onCancel();
    };

    // 处理确认按钮点击
    const handleConfirm = () => {
        setShowBottomSheet(false);
        Animated.timing(bottomSheetTranslateY, {
            toValue: 300,
            duration: 300,
            useNativeDriver: true,
        }).start();
        onConfirm();
    };

    return (
        <>
            {/* 底部工具栏 */}
            {!showBottomSheet && (
                <SafeAreaView style={styles.toolbar}>
                    <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.toolbarContent}>
                        {tools.map((tool) => (
                            <TouchableOpacity
                                key={tool.key}
                                style={[styles.toolItem, currentTool === tool.key && styles.toolItemActive]}
                                onPress={() => handleToolPress(tool.key)}
                            >
                                <MaterialIcons
                                    name={tool.icon as any}
                                    size={24}
                                    color={currentTool === tool.key ? '#007AFF' : '#666'}
                                />
                                <Text style={[styles.toolLabel, currentTool === tool.key && styles.toolLabelActive]}>
                                    {tool.label}
                                </Text>
                            </TouchableOpacity>
                        ))}
                    </ScrollView>
                </SafeAreaView>
            )}

            {/* 底部弹出层 */}
            {showBottomSheet && (
                <Animated.View
                    style={[styles.bottomSheet, { transform: [{ translateY: bottomSheetTranslateY }] }]}
                >
                    <View style={styles.bottomSheetHandle} />

                    <View style={styles.bottomSheetHeader}>
                        <TouchableOpacity
                            style={styles.bottomSheetHeaderBtn}
                            onPress={handleCloseBottomSheet}
                        >
                            <MaterialIcons name="close" size={24} color="#666" />
                            <Text style={{ color: '#666' }}>取消</Text>
                        </TouchableOpacity>
                        <Text style={styles.bottomSheetTitle}>{tools.find(t => t.key === currentTool)?.label}</Text>
                        <TouchableOpacity
                            style={styles.bottomSheetHeaderBtn}
                            onPress={handleConfirm}
                        >
                            <MaterialIcons name="check" size={24} color="#3B82F6" />
                            <Text style={{ color: '#3B82F6' }}>确定</Text>
                        </TouchableOpacity>
                    </View>

                    <SafeAreaView style={styles.bottomSheetContent}>
                        {children}
                    </SafeAreaView>
                </Animated.View>
            )}
        </>
    );
}

const styles = StyleSheet.create({
    toolbar: {
        backgroundColor: '#fff',
        borderTopColor: '#ccc',
        paddingVertical: 8,
    },
    toolbarContent: {
        paddingHorizontal: 12,
    },
    toolItem: {
        alignItems: 'center',
        marginHorizontal: 16,
        opacity: 0.8,
    },
    toolItemActive: {
        opacity: 1,
    },
    toolLabel: {
        fontSize: 12,
        color: '#666',
        marginTop: 4,
    },
    toolLabelActive: {
        color: '#007AFF',
    },
    bottomSheet: {
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: '#fff',
        borderTopLeftRadius: 16,
        borderTopRightRadius: 16,
        zIndex: 9000,
    },
    bottomSheetHandle: {
        width: 32,
        height: 4,
        backgroundColor: '#E5E7EB',
        borderRadius: 2,
        alignSelf: 'center',
        marginTop: 8,
        marginBottom: 8,
    },
    bottomSheetHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 16,
        paddingVertical: 12,
        borderBottomWidth: 1,
        borderBottomColor: '#E5E7EB',
    },
    bottomSheetHeaderBtn: {
        flexDirection: 'row',
        alignItems: 'center',
        gap: 4,
    },
    bottomSheetTitle: {
        fontSize: 16,
        fontWeight: '600',
        color: '#111827',
    },
    bottomSheetContent: {
        flex: 1,
        padding: 16,
    },
});